//index.js
//获取应用实例

import {ajax} from "../../utils/httpRequest.js";
import {
  URI_UPLOADSELFIMG,
  URI_POSTALLDATA,
  URI_GETBRANCHINFO,
  URI_WANSHANGIMG,
  URI_MINGZUILIST
} from "../../utils/api.js";

Page({
  data: {
    currentindex: 0,
    url: '/images/default-head.png',
    sex: '',
    education: '',
    branchdata: [],
    information: {
      date: '',
      sexinfo: {
        sexindex: '',
        sexarray: ['男', '女']
      },
      minority: {
        minorityindex: '',
        minorityarray: []
      },
      education: {
        educationindex: '',
        //educationarray: ['', '', '', '', '','','','']
        educationarray: ['小学', '初中', '高中', '专科', '本科', '硕士', '博士', '未知']
      },
      active: true
    },
    userInfoSync: {},
    partyinfo: {
      branch_id: '',
      date: '',
      zz_time: '',
      job_id: '',
      partyaddress: '',
      organization: {
        organizationindex: '',
        organizationarray: []
      },
      post: '',
      active: true
    }
  },
  onLoad: function () {
    this.getBranchInfo();
    this.getMinZuList();
    if (this.data.currentindex == 0) {
      wx.setNavigationBarTitle({
        title: '人脸录入',
      })
    } else if (this.data.currentindex == 1) {
      wx.setNavigationBarTitle({
        title: '个人信息',
      })
    } else if (this.data.currentindex == 2) {
      wx.setNavigationBarTitle({
        title: '党员信息',
      })
    }
  },

  getMinZuList() {
    ajax.get(URI_MINGZUILIST, {}, {}, res => {
      console.log(res.data);
      this.setData({
        'information.minority.minorityarray': res.data
      })
      //console.log(this.information.o);
    });
  },

  getBranchInfo() {
    ajax.get(URI_GETBRANCHINFO, {}, {}, res => {
      this.setData({
        branchdata: res.data.branchs
      });
      let branchs_name_array = [];
      this.data.branchdata.forEach((value) => {
        branchs_name_array.push(value.branchs_name);
      });
      this.setData({
        'partyinfo.organization.organizationarray': branchs_name_array
      });
    });
  },


  // 信息录入部分开始 input onblur 事件
  getUserName: function (e) {

  },
  getUserEmail: function (e) {

  },
  getUserCard: function (e) {

  },
  getUserPosition: function (e) {

  },


  handleClick() {
    const addCurrent = this.data.currentindex + 1;
    const currentindex = addCurrent > 2 ? 0 : addCurrent;
    this.setData({
      'currentindex': currentindex
    })
  },

  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'information.date': e.detail.value
    })
  },
  bindSexChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'information.sexinfo.sexindex': e.detail.value,
      sex: parseInt(e.detail.value)+1
    });
  },
  bindMinorityChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'information.minority.minorityindex': e.detail.value
    })
  },
  bindEducationChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'information.education.educationindex': e.detail.value
    });
    // if(e.detail.value<=6){
    //   this.setData({
    //     education:parseInt(e.detail.value)+1
    //   })
    // }else {
    //   this.setData({
    //     education:0
    //   })
    // }
  },
  submitinfo(e) {
    if (this.data.information.active) {
      let formData = e.detail.value;
      console.log(formData);
      var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
      let regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (!formData.username) {
        this.showMessage('请输入您的真实名字');
        return false;
      } else if (!formData.gonghao) {
        this.showMessage('请输入您的工号');
        return false;
      } else if (!formData.useremail) {
        this.showMessage('请输入您的邮箱');
        return false;
      } else if (!regEmail.test(formData.useremail)) {
        this.showMessage('请输入正确邮箱');
        return false
      } else if (!formData.usercard) {
        this.showMessage('请输入您的身份证号');
        return false
      } else if (!regIdCard.test(formData.usercard)) {
        this.showMessage('您输入的身份证不正确！');
        return false
      } else if (!formData.userdate) {
        this.showMessage('请选择出生日期');
        return false
      } else if (!formData.sexinfo) {
        this.showMessage('请选择性别');
        return false;
      } else if (!formData.minority) {
        this.showMessage('请选择所在名族');
        return false;
      } else if (!formData.education) {
        this.showMessage('请选择您的学历');
        return false;
      } else if (!formData.userposition) {
        this.showMessage('请输入您的工作岗位');
        return false;
      }
      wx.showModal({
        title: '温馨提示',
        content: '您的个人信息已经提交',
        showCancel: false,
        confirmText: '下一步',
        confirmColor: '#0d77e4',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              currentindex: 2,
              userInfoSync: formData
            });
            wx.setNavigationBarTitle({
              title: '党员信息',
            })
          }
        }
      })
    } else {
      console.log('您还没有输入信息');
    }
  },
  showMessage(text) {
    wx.showToast({
      title: text,
      icon: 'none',
      duration: 2000
    })
  },
  // 信息录入部分结束


  // 党员信息录入部分开始------------------------------------------------------

  bindJoinDateChange: function (e) {
    this.setData({
      'partyinfo.date': e.detail.value
    })
  },
  zz_timeChange(e){
    this.setData({
      'partyinfo.zz_time': e.detail.value
    })
  },
  bindOrganizationChange: function (e) {
    this.setData({
      'partyinfo.organization.organizationindex': e.detail.value,
    });
    let branch_name = this.data.partyinfo.organization.organizationarray[e.detail.value];
    this.data.branchdata.forEach((value) => {
      if (value.branchs_name == branch_name) {
        this.setData({
          'partyinfo.branch_id': value.id,
          'partyinfo.post': ''
        });
        wx.setStorageSync('jobNameArray', value.titles);
        wx.setStorageSync('jobStr', '');
        wx.setStorageSync('jobIdStr', '');
      }
    });
  },
  getBranchInfo2() {
    ajax.get(URI_GETBRANCHINFO, {}, {}, res => {
      console.log(res.data);
      this.setData({
        branchdata: res.data.branchs
      });
      let branchs_name_array = [];
      this.data.branchdata.forEach((value) => {
        branchs_name_array.push(value.branchs_name);
      });
      this.setData({
        'partyinfo.organization.organizationarray': branchs_name_array
      });
      if(!this.data.partyinfo.organization.organizationarray){
        wx.showToast({
          title: '您所在公司没有所属组织',
          icon: 'none',
          duration: 2500
        });
        return false;
      }
    });
  },
  clickBranch(){
    if(!this.data.partyinfo.organization.organizationarray){
      this.getBranchInfo2();
    }
  },
  choose_job_item() {
    if (!this.data.partyinfo.branch_id) {
      wx.showModal({
        content: '请您先选择所属组织再选择党内职务',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#0d77e4',
        success: (res) => {
          if (res.confirm) {

          }
        }
      })
    }else {
      wx.navigateTo({
        url: '/pages/choose_job/choose_job',
      })
    }
  },
  // bindPostChange: function (e) {
  //   //console.log('picker发送选择改变，携带值为', e.detail.value)
  //   this.setData({
  //     'partyinfo.post.postindex': e.detail.value
  //   });
  //   let select_job_name = this.data.partyinfo.post.postarray[e.detail.value];
  //   // console.log(select_job_name);
  //   // console.log(this.data.branch_id);
  //   this.data.branchdata.forEach((value) => {
  //     if (value.id == this.data.partyinfo.branch_id) {
  //       value.titles.forEach((titles) => {
  //         if (titles.job_name == select_job_name) {
  //           this.setData({
  //             'partyinfo.job_id': titles.id
  //           })
  //         }
  //       })
  //     }
  //   });
  //   // console.log(this.data.partyinfo.branch_id);
  //   // console.log(this.data.partyinfo.job_id);
  // },
  submitPartyInfo(e) {
     //console.log(e.detail.formId);
    var formId = e.detail.formId;
    if (this.data.partyinfo.active) {
      let partyData = e.detail.value;
      if (!partyData.joinDate) {
        this.showMessage('请选择入党时间');
        return false;
      } else if (!partyData.organization) {
        this.showMessage('请选择所属组织');
        return false;
      } else if (!partyData.post) {
        this.showMessage('请选择党内职务');
        return false;
      } else if (!partyData.partymember) {
        this.showMessage('请输入您的组织关系所在地');
        return false;
      }
      //console.log(this.data.userInfoSync);
      ajax.post(URI_POSTALLDATA, {
        phone: wx.getStorageSync('tel'),
        user_card: this.data.userInfoSync.usercard,
        email: this.data.userInfoSync.useremail,
        job_id: this.data.partyinfo.job_id,
        faceImg: this.data.url,
        name: this.data.userInfoSync.username,
        birthday: this.data.userInfoSync.userdate,
        sex: this.data.sex,
        mz_id: this.data.userInfoSync.minority,
        edu: this.data.information.education.educationindex <= 6 ? parseInt(this.data.information.education.educationindex) + 1 : '0',
        post: this.data.userInfoSync.userposition,//工作岗位
        join_time: partyData.joinDate,
        branch_id: this.data.partyinfo.branch_id,
        org_address: partyData.partymember,
        uid: wx.getStorageSync('uid'),
        zz_time:partyData.zz_time,
        job_number:this.data.userInfoSync.gonghao,
        form_id:formId
      }, {}, res => {
        console.log(res.data.section1.id);
        wx.setStorageSync('dangyuan_id', res.data.section1.id);
        wx.showModal({
          content: '恭喜您完成档案填写',
          showCancel: false,
          confirmText: '立即查看',
          confirmColor: '#0d77e4',
          success: (res) => {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/user_manage/user_manage',
              })
            }
          }
        })
      })

    } else {
      console.log('您还没有输入信息');
    }
  },
  // 党员信息录入部分结束
  //-------------上传图片--人脸识别---------------------------------------------------
  bindPhone: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        wx.showToast({
          title: '人脸正在识别中请稍后！！',
          icon: 'loading',
          duration: 5000,
          mask: false
        })
        var tempFilePaths = res.tempFilePaths[0];
        ajax.get('https://api.cloudcpc.com/home/Qiniu/upload', {}, {}, res => {
          console.log(res.token);
          that.comenUploadFun(res.token, tempFilePaths)
        })
      }
    })
  },
  comenUploadFun(token, path) {
    let that = this;
    wx.uploadFile({
      url: 'https://upload.qiniup.com',
      // url: 'https://up-z2.qiniup.com',
      filePath: path,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      formData: {
        token: token
      },
      success: (res) => {
        var data = JSON.parse(res.data);
        // var upladurl = 'http://pjapi6s2a.bkt.clouddn.com/' + data.key;
        var upladurl = 'http://oss.co-links.com/' + data.key;
        this.postImgInfo(upladurl);
      },
      fail: (error) => {
        wx.showModal({
          title: "提示",
          content: '您的人脸识别失败，请重试!',
          showCancel: false,
          confirmColor: '#0d77e4',
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      }
    })
  },

  postImgInfo(url) {
    ajax.post(URI_UPLOADSELFIMG, {
      uid: wx.getStorageSync('uid'),
      url: url
    }, {}, res => {
      wx.hideToast();
      console.log(res);
      if (res.type == 3) {
        ajax.post(URI_WANSHANGIMG, {
          dangyaun_id: wx.getStorageSync('dangyuan_id'),
          facedata: url
        }, {}, res => {
          // console.log(res);
          let that = this;
          this.setData({
            url: url
          });
          wx.showModal({
            title: '提示',
            content: '您的人脸识别已经成功！',
            showCancel: false,
            confirmColor: '#0d77e4',
            confirmText: '下一步',
            success: (res) => {
              if (res.confirm) {
                this.setData({
                  currentindex: 1
                })
              }
              wx.setNavigationBarTitle({
                title: '个人信息',
              })
            }
          })
        });
      } else {
        wx.showModal({
          title: "提示",
          content: '您的人脸识别失败，请重试。',
          showCancel: false,
          confirmColor: '#0d77e4',
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBranchInfo();
    this.setData({
      'partyinfo.job_id': wx.getStorageSync('jobIdStr'),
      'partyinfo.post':wx.getStorageSync('jobStr')
    })
  }

})